#include "tablewidget.h"
#include <QMouseEvent>
#include <QApplication>

TableWidget::TableWidget(QWidget *parent) :
    QTableWidget(parent)
{
    setAcceptDrops(true);
    setDragEnabled(true);
}
void TableWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    startPos = event->pos();
    QTableView::mousePressEvent(event);
}
void TableWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        int distance = (event->pos() - startPos).manhattanLength();
        if (distance >= QApplication::startDragDistance())
        performDrag();
    }
    QTableWidget::mouseMoveEvent(event);
}
void TableWidget::performDrag()
{
    QTableWidgetItem *item = currentItem();
    if (item)
    {
        QMimeData *mimeData = new QMimeData;
        mimeData->setText(item->text());
        QDrag *drag = new QDrag(this);
        drag->setMimeData(mimeData);
        drag->setPixmap(QPixmap(":/images/person.png"));
        if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
        delete item;
    }
}
void TableWidget::dragEnterEvent(QDragEnterEvent *event)
{
    TableWidget *source =
    qobject_cast<TableWidget *>(event->source());
    if (source && source != this)
    {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}
void TableWidget::dragMoveEvent(QDragMoveEvent *event)
{
    TableWidget *source =
    qobject_cast<TableWidget *>(event->source());
    if (source && source != this)
    {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}
void TableWidget::dropEvent(QDropEvent *event)
{
    TableWidget *source =
    qobject_cast<TableWidget *>(event->source());
    if (source && source != this)
    {
        QTableWidgetItem *f = new QTableWidgetItem(event->mimeData()->text());
        //QCursor::pos();
        setCurrentItem(f);
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}


